/*
	Created: 2012-06-29 sam.huang
*/

/*
 * ====================================================
 * 服务接口初始化
 */


/*
 * ====================================================
 * 页面数据定义
 */
var PAGEATTR = {
		nickname: null
		// can add more attributes here as needed
	};

var VIDEO = {
		isPlaying: false,
		isStarted: false,
		baseCurrentTime:0,
		resetVideo:true
	};

var TYPE = {
		ppt:"TYPE_PPT_TURNING"//PPT、章节
	};

function initPageParam(obj){
	PAGEATTR.nickname = obj.nickname;
	info("[initPageParam] nickname = " + PAGEATTR.nickname);
}

/*
 * ====================================================
 */
$(function(){
	$("#qaBtn").bind("click",function(){
		$("#qaView").toggle();
	});
	$("#leaveMsgBtn").bind("click",function(){
		$("#leaveMessage").toggle();
	});
});



/*
 * ====================================================
 * 视频
 */
$(function(){
	$("#video").bind('playing', onPlaying);
	$("#video").bind('ended', onEnded);
	$("#video").bind('pause', onPause);
	$("#video").bind('seeked', onSeeked);
	$("#video").bind('canplay', onCanplay);
	
	window.addEventListener("orientationchange", function() {
		fixFullscreen($(".fullScreen"));
	});
});

function onCanplay(){
	if(VIDEO.resetVideo){
		VIDEO.baseCurrentTime = $("#video")[0].currentTime;
		VIDEO.resetVideo = false;
		info("------set video's base currentTime---------", VIDEO.baseCurrentTime);
	}
}

//开始播放时执行
function onPlaying(){
	info("[ipad-live][video] video playing!!");
	VIDEO.isPlaying = true;
	VIDEO.isStarted = true;
	Sch.start(videoPlayedTime);
	
	info("[ipad-live][onPlaying] currentTime: "+$("#video")[0].currentTime+"s");
	info("[ipad-live][onPlaying] base currentTime: "+VIDEO.baseCurrentTime+"s");
}

//视频停止后执行
function onEnded(){
	info("[ipad-live][video] video ended!!");
	VIDEO.isPlaying = false;
	Sch.stop();
	$("#pptImg").attr("src",staticPrefix+"/static/zh_CN/images/ipad/images/completed.jpg");
}

//视频暂停后执行
function onPause(){
	info("[ipad-live][video] video pause!!");
	VIDEO.isPlaying = false;
	Sch.stop();
}

function onSeeked(){
	info("[ipad-vod][onSeeked] seeked!! currentTime:", $("#video")[0].currentTime);
	var time = videoPlayedTime();
	Sch.seek(time, TYPE.ppt);
}

//视频已播放时长，单位毫秒
function videoPlayedTime(){
	return $("#video")[0].currentTime - VIDEO.baseCurrentTime;
}

/*
 * ====================================================
 * 文档
 */
$(function(){
	Sch.setType(TYPE.ppt, pptRelatedInHandler, pptRelatedOutHandler, Sch.TASKMODE_SUBSTITUTION);//加载PPT的任务回调处理器
});


var VideoSyncDatas = {path:null, datas:[]};


//装载视频同步数据
function loadVideoSyncDatas(resPath, data){
	VideoSyncDatas.path = resPath;
	var datas = data.pageList;
	for(var i in datas){
//		{no:1, begin:"5", end:"7", title:"Gensee网络会议1", pptName:"20120203151816.png", time:"0:05"}
		var data = datas[i];
		var videoSyncData = {};
		videoSyncData.no = Number(i)+1;
		videoSyncData.begin = Number(data.startTime);
		videoSyncData.end = Number(data.endTime);
		videoSyncData.title = data.title;
		videoSyncData.pptName = data.hls;
		videoSyncData.time = formatTime(data.startTime);
		readyVideoSyncData(videoSyncData);
		
		VideoSyncDatas.datas.push(videoSyncData);
	}
	Sch.createGapTask(TYPE.ppt, 0.5);
	info("Sch taskGroup["+TYPE.ppt+"]:", Sch.getTaskGroup(TYPE.ppt));
}

function formatTime(time){
	var sec = Math.round(Number(time));
	var min = 0;
	var hr = 0;
	if(sec<60){
		var sSec = sec<10?"0"+sec:sec;
		return "0:"+sSec;
	}else{
		min = Math.floor(sec/60);
		sec = sec%60;
		var sSec = sec<10?"0"+sec:sec;
		if(min<60){
			return min+":"+sSec;
		}else{
			hr = Math.floor(min/60);
			min = min%60;
			var sMin = min<10?"0"+min:min;
			return hr+":"+sMin+":"+sec;
		}
	}
}


function readyVideoSyncData(videoSyncData){
	schPptRelated(videoSyncData);
	readySection(videoSyncData);
}

//添加一个文档调度任务
function schPptRelated(videoSyncData){
	var beginPoint = videoSyncData.begin;
	var endPoint = videoSyncData.end;
	Sch.addTask(new Task(TYPE.ppt, beginPoint, endPoint, videoSyncData));
}

//文档回调处理器（供调度器任务回调）
function pptRelatedInHandler(videoSyncData){
	if(videoSyncData){
		showPPT(videoSyncData);
	}else{
		clearPPT();
	}
}

function showPPT(videoSyncData){
	info("[ipad-vod][showPPT] videoSyncData:", videoSyncData);
	$("#pptImg").attr("src", VideoSyncDatas.path + videoSyncData.pptName);
	$("#pptImg").show();
	focusSection(getSectionByIdx(videoSyncData.no - 1));
}

//文档回调处理器（供调度器任务回调）
function pptRelatedOutHandler(data){
	clearPPT();
}

function clearPPT(){
	info("[ipad-vod][clearPPT] !");
	$("#pptImg").attr("src","");
	$("#pptImg").hide();
	$("#charpterContainer").find(".current").removeClass("current");
}
/*
 * ====================================================
 * 视窗大小适应，视窗交换，视窗全屏等用户接口（由触摸、滑动、手势等触发）
 */
$(function(){
	
	$("#videoBtn").bind("click", videoToMainView);
	$("#docBtn").bind("click", docToMainView);
	$("#sectionBtn").bind("click", sectionToMainView);
	
	bindPptFullscreenGesture();
//	bindVideoFullscreenGesture();
	bindVideoTouchwipe();
	bindPptTouchwipe();
});

function mainViewIsDoc(){
	return $("#pptView").parent().is("#mainView");
};

function mainViewIsVideo(){
	return $("#videoView").is(".videoMove");
}

function enterFullscreen($obj, foo){
	debug("--- enter fullscreen");
	$obj.addClass("fullScreen");
}

function fixFullscreen($fullscreenElem){
	if(Nav.isOS5_0 && $fullscreenElem){
		if($fullscreenElem.is("#pptImgView")){
			window.scrollTo(0,0);
			return;
		}
		
		var cssObj;
		$fullscreenElem.attr("style","");
		var oldTop = $fullscreenElem.position().top;
		if(isLandscape()){
			cssObj = {top:(Number(window.pageYOffset)+Number(oldTop))+"px", height: (674 - Nav.browserDiffOffset)+"px"};
		}else{
			cssObj = {top:(Number(window.pageYOffset)+Number(oldTop))+"px", height: (928 - Nav.browserDiffOffset)+"px"};
		}
		$fullscreenElem.css(cssObj);
	}
}

function existFullscreen($obj){
	debug("--- exist fullscreen");
	$obj.removeClass("fullScreen");
	$obj.css({top:"", height:""});
}

//请求将视频移位到主视窗
function videoToMainView(){
	if($("#videoView").is(".videoMove")) return; //已移位到主视窗
	
	moveVideo2mainView(); //视频移位
	moveEle("pptView", "rtView"); //文档加载到右上视窗
	if(!$("#sectionView").parent().is("#rbView")){ //问答是否在右下视窗
		moveEle("sectionView", "rbView"); //问答加载到右下视窗
	}
}

//请求将文档加载到主视窗
function docToMainView(){
	debug("--- doc to main view");
	if($("#pptView").parent().is("#mainView")) return;
	
	moveEle("pptView", "mainView");
	if($("#videoView").is(".videoMove")){
		moveVideo2rtView();
	}else if(!$("#sectionView").parent().is("#rbView")){
		moveEle("sectionView", "rbView");
	}
}

//请求将问答加载到主视窗
function sectionToMainView(){
	if($("#sectionView").parent().is("#mainView")) return;
	
	moveEle("sectionView", "mainView");
	moveEle("pptView", "rbView");
	if($("#videoView").is(".videoMove")){
		moveVideo2rtView();
	}
}

//视频移位到主视窗
function moveVideo2mainView(){
	$("#videoView").addClass("videoMove");
	$("#videoWrap").removeClass("videoMin");
	$(".videoCntR").removeClass("videoCntRW");
}

//视频移位到右上视窗
function moveVideo2rtView(){
	$("#videoView").removeClass("videoMove");
	$("#videoWrap").addClass("videoMin");
	$(".videoCntR").addClass("videoCntRW");
	$("#videoWrap").css("position","");
}

//将元素移到模板元素内部，作为前置节点，并进行大小适应调整
function moveEle(eleId, destId){
	var ele = $("#"+eleId);
	var dest = $("#"+destId);
	dest.prepend(ele);
	if(destId=="mainView"){
		enlarge(eleId);
	}else{
		downsize(eleId);
	}
}

//放大（video通过移位完成，所有未包含视频逻辑）
function enlarge(eleId){
	if(eleId == "pptView"){
		$("#pptImgView").addClass("pptBigH");
		$("#pptImgView").removeClass("pptSmallH");
	}else if(eleId == "sectionView"){
		$("#qaMyList").removeClass("askSmallH");
		$("#qaAllList").removeClass("askSmallH");
		$("#qaMyList").addClass("askBigH");
		$("#qaAllList").addClass("askBigH");
	}else{
		error("[ipad-live][enlarge] eleId 不合法："+eleId);
	}
}

//缩小（video通过移位完成，所以未包含视频逻辑）
function downsize(eleId){
	if(eleId == "pptView"){
		$("#pptImgView").removeClass("pptBigH");
		$("#pptImgView").addClass("pptSmallH");
	}else if(eleId == "sectionView"){
		$("#qaMyList").removeClass("askBigH");
		$("#qaMyList").addClass("askSmallH");
		$("#qaAllList").removeClass("askBigH");
		$("#qaAllList").addClass("askSmallH");
	}else{
		error("[ipad-live][downsize] eleId 不合法："+eleId);
	}
}

/*
 * ====================================================
 * 提示框
 */
$(function(){
	initInfoDialog();
});

function initInfoDialog(){
	w2=$(".nipad").width()/2;
	h2=$(".nipad").height()/2;
	w3=$("#popDivId").width()/2;
	h3=$("#popDivId").height()/2;
	$("#popDivId").css({left:w2-w3,top:h2-h3});
	$("#winClose").click(function(){
			$("#popDivId").hide();
			$("#idCover").hide();
		});
}

/*
 * ====================================================
 * 调节日志级别
 */
$("#about").bind("gestureend", function(){
	if(event.scale > 1.2){
		if(LOG && LOG.level<4){
			LOG.level += 1;
		}
	}else if(event.scale < 0.8){
		if(LOG && LOG.level>0){
			LOG.level -= 1;
		}
	}
});

/*
 *!====================================================!
 */